// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq.Expressions;

namespace SnapObjects.Commons
{
    public static class LinqExtentions
    {
        public static Expression<Predicate<TModel>> And<TModel>(
            this Expression<Predicate<TModel>> expression, Expression<Predicate<TModel>> expression1)
        {
            var parameter = expression.Parameters[0];

            var access = new ParameterAccessor(parameter);

            return Expression.Lambda<Predicate<TModel>>(
                Expression.AndAlso(access.Visit(expression.Body), access.Visit(expression1.Body)), parameter);
        }


        public static Expression<Predicate<TModel>> Or<TModel>(
            this Expression<Predicate<TModel>> expression, Expression<Predicate<TModel>> expression1)
        {
            var parameter = expression.Parameters[0];

            var access = new ParameterAccessor(parameter);

            return Expression.Lambda<Predicate<TModel>>(
                Expression.OrElse(access.Visit(expression.Body), access.Visit(expression1.Body)), parameter);
        }

        public static Expression<Func<TModel, bool>> And<TModel>(
            this Expression<Func<TModel, bool>> expression, Expression<Func<TModel, bool>> expression1)
        {
            var parameter = expression.Parameters[0];

            var access = new ParameterAccessor(parameter);

            return Expression.Lambda<Func<TModel, bool>>(
                Expression.AndAlso(access.Visit(expression.Body), access.Visit(expression1.Body)), parameter);
        }


        public static Expression<Func<TModel, bool>> Or<TModel>(
            this Expression<Func<TModel, bool>> expression, Expression<Func<TModel, bool>> expression1)
        {
            var parameter = expression.Parameters[0];

            var access = new ParameterAccessor(parameter);

            return Expression.Lambda<Func<TModel, bool>>(
                Expression.OrElse(access.Visit(expression.Body), access.Visit(expression1.Body)), parameter);
        }
    }
}
